import time
from . import ui_
from . import spinner_
from . import chess
from . import ajax

class Controller(ui_.Controller):
	def __init__(self, chess_board):
		self.chess_board = chess_board
		elt = chess_board.elt()
		filename = javascript.prompt('请输入csv文件名').data()
		if filename is None:
			return
		if not filename.endswith('.csv'):
			filename = filename + '.csv'
		self.dragging_chess = None
		self.player = 'Red'
		try:
			history = ajax.rpc.rpc_load_csv(filename)
			for i,(i1,j1,i2,j2) in enumerate(history):
				time.sleep(2) # 观看时每步延迟
				if self.player=='Black':
					i1,j1,i2,j2 = 8-i1,9-j1,8-i2,9-j2
				chess1 = self.chess_board.board_map[(i1,j1)]
				succ, captured = self._move_chess_to(chess1, i2, j2)
				assert succ
				px, py = self.chess_board.plate.pos_to_pixel(i1, j1)
				self._move_chess_img(chess1, px, py)
				if captured is not None:
					captured = captured.type
				print(f'{i+1}/{len(history)}',self.player,chess1.type,i1,j1,i2,j2,captured)
				self.player = 'Red' if self.player=='Black' else 'Black'
		except RuntimeError as ex:
			javascript.alert(str(ex))

def run_app():
	chess_board = ui_.ChessBoard()
	javascript.document.body.appendChild(chess_board.elt())
	Controller(chess_board)

